Custom clone function in JavaScript
We can easily clone an object in JavaScript using the structuredClone
method, Ramda's clone
, or Lodash's cloneDeep
.
However, writing our own cloning function can lead to much better performances.
For the Codewars kata Win at Skyjo, the function getPlayersColumnsClone
deep clones an array of five arrays, themselves arrays of four arrays, themselves arrays of three arrays of simple objects with four properties.
Here's how this function performs 100,000 cloning operations compare to other methods:
getPlayersColumnsClone
0.06 sstructuredClone
2.54 sLodash.cloneDeep
4.68 sRamda.clone
8.62 sBenchmark implementation
import Lodash from "lodash";
import * as Ramda from "ramda";
const NUMBER_OF_PLAYERS = 5;
const NUMBER_OF_COLUMNS = 4;
const NUMBER_OF_ROWS = 3;
const playersColumns = Array.from({ length: NUMBER_OF_PLAYERS }, () =>
Array.from({ length: NUMBER_OF_COLUMNS }, (_, x) =>
Array.from({ length: NUMBER_OF_ROWS }, (__, y) => ({
x,
y,
card: 0,
visible: false,
})),
),
);
const cloneFunctions = [
Ramda.clone,
Lodash.cloneDeep,
structuredClone,
getPlayersColumnsClone,
];
for (const cloneFunction of cloneFunctions) {
console.info(`Cloning with '${cloneFunction.name}'...`);
const startTime = performance.now();
for (let i = 0; i < 100_000; i++) {
cloneFunction(playersColumns);
}
const duration = Math.round((performance.now() - startTime) / 10) / 100;
console.info(`Took ${duration} s`);
}